package com.example.cloud.utils;

import com.example.cloud.constants.CommonConstants;
import com.example.cloud.model.dto.Result;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * Created by wangtao on 2018/3/13.
 */
@Configuration
public class CacheUtil {
    @Value("${client.secret}")
    private String secret;
    @Value("${service.auth-url}")
    private String authService;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取client-token并缓存
     * @param name
     * @return
     */
    @Cacheable(cacheNames = "clientToken")
    public String getClientToken(String name){
        String clientToken = "";
        String sign = DigestUtils.md5Hex(name + secret).toUpperCase();
        String url = authService + "/authorize?name=" + name + "&secret=" + sign;
        Result result = restTemplate.postForObject(url, null, Result.class);
        if (result.getCode().equals(CommonConstants.SUCCESS)) {
            clientToken = String.valueOf(result.getData());
        }
        return clientToken;
    }

    /**
     * 清空指定缓存中所有项目,也可通过key指定要删除的某一项缓存
     */
    @CacheEvict(cacheNames = "clientToken",allEntries = true)
    public void clearToken(){
    }
}
